<template>
  <div v-loading="flyLoading" :class="{'pb55':device!=='mobile', 'mobile-create mobile-small-padding': showMobilePage }" class="page-container">
    <div style="min-height: calc(100vh - 120px)">
      <el-form v-if="isModify" ref="modifyExplainRef" :model="modifyExplain" :rules="modifyExplainRules" :label-position="formAlign" label-width="100px">
        <el-form-item label="修改说明" prop="content">
          <el-input v-model.trim="modifyExplain.content" :maxlength="1000" resize="none" style="max-width: 240px" placeholder="请输入修改说明" type="textarea" size="small" />
        </el-form-item>
      </el-form>
      <CreateSupplierInfo ref="supplierInfoRef" v-model="supplierInfo" :is-edit="isEdit" :row-span="12" is-create-supplier />
      <DetailTabs v-model="tabIndex" :tabs="tabList" />
      <CreateOtherInfo v-show="tabIndex === 0" ref="otherInfoRef" v-model="supplierInfo" :is-edit="isEdit" :row-span="12" is-create-supplier />
      <AccountInfo
        v-show="tabIndex === 1"
        ref="accountInfoRef"
        v-model="accountsInfoList"
        :supplier-info="supplierInfo"
        :row-span="12"
        :is-modify="isModify"
        :form-fly-user="Boolean(flyUserId)"
        :show-mobile-page="showMobilePage"
        open-real-time-verify
        page-from="supplierManage"
        class="supplier-account-info"
        is-hidden-title
        style="margin-bottom: 20px;"
        @showBadge="badgeChange(1, $event)"/>
      <CreateAccountList
        v-show="tabIndex === 2"
        ref="accountListRef"
        :is-company="isCompany"
        v-model="accountsReceivable"
        :add-btn-style="{
          height:'30px',width:'93px',padding: '0 8px',background: '#fff',fontSize: '14px',color: '#406eff',
          position: 'absolute',right: '0px',top: showMobilePage ? '12px' : '-40px',border: '1px solid #406eff', fontWeight: 'bold'
        }"
        show-add-btn
        open-real-time-verify
        class="create-account-list"
        is-hidden-title
        is-create-supplier
        style="margin-bottom: 20px;"
        @showBadge="badgeChange(2, $event)"/>
      <AddressManage v-show="tabIndex === 3" ref="addressManageRef" :show-mobile-page="showMobilePage" v-model="supplierInfo.addressList" class="address-manage" />
      <SelectApprover ref="selectApproverRef" @approverSelected="supplierModify" />
    </div>
    <fixed-pagination>
      <div class="center">
        <el-button v-if="!isModify" :loading="addLoading" size="small" type="primary" @click="submit(false)">保存</el-button>
        <el-button v-else size="small" type="primary" @click="submit(false)">发起审批</el-button>
        <!-- <el-button size="small" type="info" @click="submit(true)">保存草稿</el-button> -->
        <el-button class="cancel-btn-style" size="small" @click="goBack">返回</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>

<script>
// components
import CreateSupplierInfo from '@/components/SupplierComponent/createSupplierInfo';
import CreateAccountList from '@/components/SignUp/createAccountList';
import CreateOtherInfo from '@/components/SupplierComponent/createOtherInfo';
import AccountInfo from '@/components/SignUp/accountInfo';
import SelectApprover from '../components/selectApprover';
import AddressManage from '@/components/SupplierComponent/addressManage';
import DetailTabs from '@/components/Common/baseComponent/DetailTabs';
// tool
import { mapState } from 'vuex';
import ElMessage from '@/utils/message';
import { generateUUID } from '@/utils/tools';
// api
import { supplierAdd, supplierEdit, supplierInfo, supplierModify, supplierModifyDetail } from '@/api/supplier';
import { getPlatformConfig } from '@/api/signUp';
import { SUPPLIER_DETAIL_TYPE, SUPPLIER_MODIFY_STATUS } from '@/utils/const/supplier';
import flyMixins from '@/mixins/flyUser';
import mobileCreate from '@/mixins/mobileCreate';

export default {
  components: { CreateSupplierInfo, CreateAccountList, AccountInfo, SelectApprover, CreateOtherInfo, DetailTabs, AddressManage },
  mixins: [flyMixins, mobileCreate],
  props: {
    pageType: { // 如果值为 component 则这个页面作为组建使用
      type: String,
      default: ''
    },
    extendParams: { // 如果作为组建使用时，额外参数
      type: Object,
      default: null
    },
    fromFlyUser: { // 飞来用户新建供应商
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tabIndex: 0,
      supplierInfo: { // 供应商信息
        createUser: '',
        departmentId: '',
        supplierType: 0,
        channelName: '',
        cooperationStatus: 0,
        taxpayerIdentificationNumber: '',
        publishedStatus: 0,
        sex: 0,
        taxRate: '',
        region: '',
        address: '',
        phone: '',
        wxCode: '',
        idCard: [],
        signedScreenshot: [],
        remark: '',
        tag: [],
        signStatus: '',
        addressList: []
      },
      accountsReceivable: { // 收款账户
        isOpenCloud: true,
        list: []
      },
      tabList: [
        { id: 0, name: '' },
        { id: 1, name: '账号信息' },
        { id: 2, name: '收款账户' },
        { id: 3, name: '地址管理' }
      ],
      accountsInfoList: [], // 账号信息
      isEdit: false,
      isModify: false,
      modifyId: '', // 审批单记录id
      addLoading: false,
      modifyExplain: {
        content: ''
      },
      flyUserId: '',
      flyLoading: false
    };
  },
  computed: {
    ...mapState({
      'device': state => state.app.device,
      'userInfo': state => state.user.userInfo
    }),
    isCompany() { // 是否是公司类型
      return this.supplierInfo.supplierType === 1;
    },
    modifyExplainRules() {
      return {
        content: [{ required: true, trigger: 'blur', message: '请输入修改说明' }]
      };
    },
    infoTabName() {
      return this.supplierInfo.supplierType === 0 ? '个人信息' : '公司信息';
    },
    source() {
      return this.fromFlyUser ? 3 : 1;
    },
    rowSpan() {
      // 原飞来用户列表点击新建供应商表单是2列，飞来用户详情点批量操作新建供应商表单是3列，有UI问题，改成都是2列
      return this.fromFlyUser ? 12 : 8;
    }
  },
  created() {
    this.flyUserId = Number(this.$route.query.flyUserId) || '';// 飞来用户ID
    const id = this.$route.query.id;
    this.modifyId = this.$route.query.modifyId || '';
    this.isModify = !!this.$route.query.isModify;
    this.tabList[0].name = this.infoTabName;
    if (id && !this.pageType) {
      this.id = id;
      this.isEdit = true;
      this.getData();
    } else {
      if (this.pageType && this.extendParams && this.extendParams.flyUserId) {
        this.flyUserId = Number(this.extendParams.flyUserId);
      }
      this.isEdit = false;
      if (this.flyUserId) {
        this.getUserInfo();
      }
    }
    this.supplierInfo.source = this.source;
  },
  methods: {
    badgeChange(index, status) {
      this.$set(this.tabList[index], 'showBadge', status);
    },
    getData() {
      const queryApi = this.modifyId ? supplierModifyDetail : supplierInfo;
      const id = this.modifyId ? this.modifyId : this.id;
      queryApi(id).then(res => {
        if (res.data) {
          this.isModify && (this.modifyExplain.content = res.data.modifyDesc);
          const accountsInfoList = res.data.accountsInfoList;
          accountsInfoList.forEach(i => {
            if (i.accountsInfo.cooperationDepartmentName) {
              i.accountsInfo.cooperationDepartment = i.accountsInfo.cooperationDepartmentName.map(j => j.id);
            } else {
              i.accountsInfo.cooperationDepartment = [];
            }
            i._uuid = generateUUID();
            if (i.accountsInfo.orderPlatformId) {
              this.getDynamic(i.accountsInfo.orderPlatformId, i);
            } else {
              this.$set(i.accountsInfo, 'dynamicKey', []);
              this.$set(i.priceInfo, 'dynamicKey', []);
            }
            if (i.contractInfo && i.contractInfo.signStartDate) {
              i.contractInfo.signDate = [i.contractInfo.signStartDate, i.contractInfo.signEndDate];
            }
          });
          this.accountsReceivable = res.data.accountsReceivable;
          this.accountsInfoList = res.data.accountsInfoList;
          delete res.data.accountsReceivable;
          delete res.data.accountsInfoList;
          this.supplierInfo = res.data;
        }
      });
    },
    submit(isDraft = false) {
      const params = JSON.parse(JSON.stringify(this.supplierInfo));
      params.accountsReceivable = JSON.parse(JSON.stringify(this.accountsReceivable));
      params.accountsInfoList = JSON.parse(JSON.stringify(this.accountsInfoList));
      params.accountsInfoList.forEach(i => {
        if (i.contractInfo && i.contractInfo.signDate) {
          i.contractInfo.signStartDate = i.contractInfo.signDate[0];
          i.contractInfo.signEndDate = i.contractInfo.signDate[1];
          delete i.contractInfo.signDate;
        }
        if (i.accountsInfo.fansNum)i.accountsInfo.fansNum = Number(i.accountsInfo.fansNum);
        if (i.priceInfo.guaranteePrice) i.priceInfo.guaranteePrice = Number(i.priceInfo.guaranteePrice);
        if (i.priceInfo.profitSharingRatio) i.priceInfo.profitSharingRatio = Number(i.priceInfo.profitSharingRatio);
      });
      if (this.flyUserId) {
        params.flyUserId = this.flyUserId;
      }
      const promise = [];
      if (!isDraft) {
        if (this.isModify) {
          const modifyExplainValid = new Promise((resolve, reject) => {
            this.$refs['modifyExplainRef'].validate(valid => {
              valid ? resolve(valid) : reject();
            });
          });
          promise.push(modifyExplainValid);
        }
        this.isModify && promise.push();
        promise.push(this.$refs.supplierInfoRef.validateForm());
        if (this.$refs.accountListRef) {
          promise.push(this.$refs.accountListRef.validate());
        }
        if (this.$refs.accountInfoRef) {
          promise.push(this.$refs.accountInfoRef.validateForm());
        }
        if (this.$refs.otherInfoRef) {
          promise.push(this.$refs.otherInfoRef.validateForm());
        }
      }
      if (params.addressList) {
        params.addressList = this.supplierInfo.addressList.filter(it => it.contacts || it.phoneNo || it.province || it.address || it.remark);
      }
      Promise.all(promise).then(() => {
        if (this.isModify) {
          // 仅审核中的申请的无需再次选择审批人
          if (this.modifyId && this.supplierInfo.approvalStatus === SUPPLIER_MODIFY_STATUS.PENDING) {
            const approverId = this.supplierInfo.approverId;
            if (!approverId) {
              this.$message.warning('无法获取审批人id');
              return;
            }
            this.supplierModify(approverId);
          } else {
            this.selectApproverShow();
          }
        } else if (this.isEdit) {
          this.edit(params);
        } else {
          this.add(params);
        }
      }).catch(() => {
        this.showErrMsg();
      });
    },
    async showErrMsg() {
      let msg = '';
      await this.$refs.supplierInfoRef.validateForm().catch(() => {
        msg = '【基础信息】未填写完整，请补充后再保存';
      });
      !msg && this.tabList[1].showBadge && (msg = '【账号信息】未填写完整，请补充后再保存');
      !msg && this.tabList[2].showBadge && (msg = '【收款账户】未填写完整，请补充后再保存');
      ElMessage.warning(msg || '请检查信息是否填写完整');
    },
    add(params) {
      this.addLoading = true;
      supplierAdd(params).then(res => {
        this.addLoading = false;
        if (res.code === 200) {
          ElMessage.success('新建成功');
          if (this.pageType === 'component') {
            this.$emit('submit', { id: res.data, name: params.channelName, supplierType: params.supplierType });
            return;
          }
          this.toBack();
        } else {
          ElMessage.error(res.message);
        }
      }).catch(() => {
        this.addLoading = false;
      });
    },
    edit(params) {
      this.addLoading = true;
      params.id = this.id;
      supplierEdit(this.id, params).then(res => {
        this.addLoading = false;
        if (res.code === 200) {
          ElMessage.success(this.isModify ? '发起审批成功' : '编辑成功');
          // this.toBack();
          this.$router.push({
            name: 'supplierManageDetail',
            params: { id: params.id }
          });
        } else {
          ElMessage.error(res.message);
        }
      }).catch(() => {
        this.addLoading = false;
      });
    },
    toBack() {
      this.$router.push({
        name: 'supplierManage'
      });
    },
    // tool
    getRequired(dynamicKey) { // 获取必填字段
      const requiredModel = {};
      dynamicKey.forEach(i => {
        if (i.required) {
          const type = i.inputType === 0 ? '输入' : '选择';
          const validateType = (msg, item) => {
            return (rule, value, callback) => {
              if (item && (item.value || item.value === 0)) {
                callback();
              } else {
                callback(new Error(msg));
              }
            };
          };
          requiredModel[i.name] = [{ required: true, trigger: 'change', validator: validateType(`请${type}${i.name}`, i) }];
        }
      });
      return requiredModel;
    },
    selectApproverShow() {
      this.$refs['selectApproverRef'].init();
    },
    supplierModify(approverId) {
      const params = JSON.parse(JSON.stringify(this.supplierInfo));
      // params.isDraft = isDraft;
      params.accountsReceivable = this.accountsReceivable;
      params.accountsInfoList = this.accountsInfoList;
      params.accountsInfoList.forEach(item => {
        if (item.contractInfo && item.contractInfo.signDate) {
          item.contractInfo.signStartDate = item.contractInfo.signDate[0];
          item.contractInfo.signEndDate = item.contractInfo.signDate[1];
          delete item.contractInfo.signDate;
        }
      });
      params.modifyDesc = this.modifyExplain.content;
      this.modifyId && (params.id = this.modifyId); // 修改审批单id(修改申请审批)
      params.supplierId = this.id;
      params.approverId = approverId;
      supplierModify(params).then(_ => {
        this.$message.success('操作成功');
        const routeData = { name: 'supplierManageDetail' };
        if (this.modifyId) {
          routeData.params = { id: this.modifyId };
          routeData.query = { type: SUPPLIER_DETAIL_TYPE.MODIFY };
        } else {
          routeData.params = { id: this.id };
        }
        this.$router.push(routeData);
      });
    },
    // 获取动态字段
    getDynamic(platformId, item) {
      getPlatformConfig(platformId).then((res) => {
        if (res.data && res.data.length) {
          this.setDynamic(res.data, item);
        }
      });
    },
    // 设置动态字段
    setDynamic(data, item) {
      const res = data[0].item || [];
      const accounts = res.find(i => i.name === '账号信息');
      const price = res.find(i => i.name === '价格信息');

      const accountsInfoDynamic = accounts ? accounts.item || [] : [];
      const priceInfoDynamic = price ? price.item || [] : [];
      const oldAccountDynamic = item.accountsInfo.dynamicKey || [];
      const oldPriceDynamic = item.priceInfo.dynamicKey || [];
      // 回填值
      this.handelDynamic(accountsInfoDynamic, oldAccountDynamic);
      this.handelDynamic(priceInfoDynamic, oldPriceDynamic);
      if (item) {
        this.$set(item.accountsInfo, 'dynamicKey', accountsInfoDynamic);
        this.$set(item.priceInfo, 'dynamicKey', priceInfoDynamic);
        const accountsRequiredModel = this.getRequired(item.accountsInfo.dynamicKey);
        const priceInfoRequiredModel = this.getRequired(item.priceInfo.dynamicKey);
        this.$set(item.accountsInfo, 'requiredModel', accountsRequiredModel);
        this.$set(item.priceInfo, 'requiredModel', priceInfoRequiredModel);
      }
      if (this.$refs.accountInfoRef) {
        this.$refs.accountInfoRef.clearValidate();
      }
    },
    handelDynamic(list, oldData) {
      list.forEach(i => {
        const oldItem = oldData.find(j => j.id === i.id);
        if (oldItem) {
          if (i.inputType === 1 && oldItem.inputType === 1) {
            let curOldItem = {};
            if (oldItem.options) {
              curOldItem = oldItem.options.find(j => j.value === oldItem.value);
            }
            const curNewItem = i.options.find(j => j.value === oldItem.value);
            if (curNewItem && curOldItem.label === curNewItem.label) {
              i.value = oldItem.value;
            } else {
              i.value = '';
            }
          } else if ((i.inputType === 1 && oldItem.inputType === 0) || (i.inputType === 0 && oldItem.inputType === 1)) {
            i.value = '';
          } else {
            i.value = oldItem.value;
          }
        }
      });
    },
    goBack() {
      if (this.pageType === 'component') {
        this.$emit('close');
        return;
      }
      if (this.flyUserId) {
        this.toBack();
      }
      this.$router.back();
    }
  }
};
</script>

<style lang="scss" scoped>
.page-container {
  min-height: calc(100vh - 90px);
  margin: 16px;
  padding: 24px;
  background-color: #fff;
  &.pb55 {
    padding-bottom: 55px;
  }
  .supplier-account-info {
    &::v-deep {
      .hidden-class {
        position: relative;
        margin-bottom: 16px;
      }
      .create-btn {
        position: absolute;
        top: -40px;
        right: 0px;
      }
    }
  }
  ::v-deep .item-badge {
    padding: 0;
    height: 12px;
    min-width: 12px;
    line-height: 12px;
  }
}
.mobile-create {
  .supplier-account-info {
    &::v-deep {
      .create-btn {
        position: relative;
        top: 12px;
      }
      .el-form-item__label {
        justify-content: flex-start;
      }
    }
  }
  .create-account-list {
    &::v-deep {
      .dynamic-container {
        .el-table {
          position: relative;
          top: 32px;
        }
      }
    }
  }
  .address-manage {
    &::v-deep {
      .dynamic-container {
        .el-table {
          position: relative;
          top: 40px;
        }
      }
    }
  }
  .mobile-pagination {
    .el-button {
      flex: 1;
    }
  }
}
</style>
